# -*- coding: utf-8 -*-
import sys
import os
from PyQt5.QtCore import Qt
from PyQt5.QtNetwork import QLocalSocket, QLocalServer
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QEvent

import qdarkstyle
from global_data.constant_data import ConstantData
from global_data.glabal_data import GlobalData


"""
程序启动
"""
# 获取当前脚本所在的路径
current_path = os.path.dirname(os.path.abspath(__file__))
# 设置当前路径为当前脚本所在的路径
os.chdir(current_path)
if os.getcwd().find("internal") != -1:
    ConstantData.WORK_PATH = os.path.dirname(current_path)
else:
    ConstantData.WORK_PATH = current_path
ConstantData.WORK_PATH = ConstantData.WORK_PATH.replace("\\", "/")
ConstantData.WORK_PATH_COMMON = ConstantData.WORK_PATH.replace("\\", "/")
# 初始化全局变量
GlobalData.init_config()


from pyqt_api.smart_getway_api import SmartGatewayApi
from pyqt_api.sys_tray import SystemTrayApp
from utils.dialog_utils import DialogUtils


def handle_minimize(win, event):
    # 处理窗体改变事件，如最小化和最大化
    if event.type() == QEvent.WindowStateChange:
        if win.windowState() & Qt.WindowMaximized:
            event.ignore()
        elif win.windowState() & Qt.WindowMinimized:
            win.showNomal()
            win.hide()
            return


def handle_close(win, event):
    # event.ignore()  # 窗体不可关闭
    print("关闭")


if __name__ == "__main__":
    # 实例化
    app = QApplication(sys.argv)
    serverName = 'smartGateway'
    socket = QLocalSocket()
    socket.connectToServer(serverName)
    # 如果连接成功，表明server已经存在，当前已有实例在运行
    if socket.waitForConnected(500):
        app.quit()
    else:
        localServer = QLocalServer()  # 没有实例运行，创建服务器
        localServer.listen(serverName)
        app.setStyleSheet(qdarkstyle.load_stylesheet())
        QApplication.setQuitOnLastWindowClosed(False)  # 最小化到托盘
        # 创建对象
        mainWindow = QMainWindow()

        # mainWindow.setWindowFlag(Qt.FramelessWindowHint)  # 设置窗口无边框
        # mainWindow.setAttribute(Qt.WA_TranslucentBackground)  # 设置背景透明
        # mainWindow.setWindowFlags(Qt.WindowCloseButtonHint) # z只显示关闭
        # 禁用放大
        # mainWindow.setWindowFlags(Qt.WindowMaximizeButtonHint | Qt.WindowMinimizeButtonHint)

        # mainWindow.changeEvent = lambda x: handle_minimize(mainWindow, x)
        # mainWindow.closeEvent = lambda x: handle_close(mainWindow, x)  # 连接窗口最小化信号到自定义槽函数

        # 创建ui
        pyqt_api = SmartGatewayApi(app, mainWindow)
        # 创建窗口
        mainWindow.show()
        GlobalData.SYS_APP = app
        GlobalData.SYS_WIN = mainWindow
        # # 显示托盘
        # tray = SystemTrayApp(app, mainWindow)
        # mainWindow.closeEvent = lambda:handleMinimize(mainWindow, mainWindow.event)
        sys.exit(app.exec_())
